package com.lanjiu.lib.imclient.ims;

import com.lanjiu.lib.app.App;
import com.lanjiu.lib.imclient.ims.offline.IMSOfflineMessageHandler;
import com.lanjiu.pro.business.BusinessProtocolMessageStandard;
import com.lanjiu.lib.communication.IMSConfig;
import com.lanjiu.lib.communication.event.OnEventListener;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.lib.imclient.ims.read.IMSMessageReader;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.log.Logger;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.lengthtcpheartbeat.NetworkUtil;

import org.greenrobot.eventbus.EventBus;

import io.netty.channel.Channel;

/**
 * @description:
 * @author: Panwei
 * @date: 2019/11/6 19:51
 */
public class IMSEventListener implements OnEventListener {

    private IMSMessageReader mMessageReader;

    public IMSEventListener(IMSMessageReader reader) {
        mMessageReader = reader;
    }

    @Override
    public BusinessProtocolMessageStandard.UnifiedEntranceMessage beforeDispatchMsg(Channel channel, BusinessProtocolMessageStandard.UnifiedEntranceMessage msg) {
        if (!IMSOfflineMessageHandler.isOfflineReceipt(msg)) {
            BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage cmsg = generateReceiptOfflineMessage(msg.getHead());
            Logger.print("离线列表回执消息：" + cmsg);
            channel.writeAndFlush(cmsg);
            IMSClientHelper.getInstance().waitForOfflineResponse();
        }
        return msg;
    }

    @Override
    public void dispatchMsg(BusinessProtocolMessageStandard.UnifiedEntranceMessage message) {
        if (null == message) return;
        BusinessProtocolMessageStandard.Head head = message.getHead();
        if (null == head) return;
        BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType = message.getDataType();

        int responseCode;
        String error;
        if (IMSConfig.MSG_CONTENT_TYPE_MESSAGE_SEND_FAIL == head.getMsgContentType()) {
            // 消息发送失败
            responseCode = IMSContacts.ResponseCode.FAILURE;
            error = "消息发送失败";
        } else if (IMSConfig.MSG_CONTENT_TYPE_MESSAGE_SEND_TIMEOUT == head.getMsgContentType()) {
            // 消息发送超时
            responseCode = IMSContacts.ResponseCode.TIMEOUT;
            error = "消息发送超时";
        } else if (IMSConfig.MSG_CONTENT_TYPE_MESSAGE_JCRC_FAIL == head.getMsgContentType()) {
            // CRC校验失败
            responseCode = IMSContacts.ResponseCode.FAILURE;
            error = "CRC数据校验失败";
        } else if (IMSConfig.MSG_CONTENT_TYPE_MESSAGE_NETWORK_FAIL == head.getMsgContentType()) {
            responseCode = IMSContacts.ResponseCode.NO_NETWORK;
            error = "请检查网络设置";
        } else if (IMSConfig.MSG_CONTENT_TYPE_MESSAGE_CANCEL == head.getMsgContentType()) {
            responseCode = IMSContacts.ResponseCode.CANCEL;
            error = "";
        } else {
            if (BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType.LoginProtocol == dataType
                    || BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType.RegisteredUserProtocol == dataType)
                UserPreferences.setToken(head.getToken());  // 登录时保存Token
            if (IMSConfig.STATUS_REPORT_SUCCESS.equals(head.getStatusReport())) {
                responseCode = IMSContacts.ResponseCode.SUCCESS;
                error = null;
            } else if (IMSConfig.STATUS_REPORT_REFUSE.equals(head.getStatusReport())) {
                responseCode = IMSContacts.ResponseCode.REFUSE;
                error = "消息被拒绝";
            } else {
                responseCode = IMSContacts.ResponseCode.FAILURE;
                error = null;
            }
        }
        MessageEvent event = mMessageReader.getRead(responseCode, head.getMsgType(), message, error);
        if (null != event)
            EventBus.getDefault().post(event);
    }

    @Override
    public boolean isNetworkAvailable() {
        try {
            return NetworkUtil.isConnected(App.getContext());
        } catch (Exception e) {
            return true;
        }
    }

    @Override
    public void close() {
    }

    private BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage generateReceiptOfflineMessage(BusinessProtocolMessageStandard.Head head) {
        BusinessProtocolMessageStandard.UnifiedEntranceMessage msg = BusinessProtocolMessageStandard.UnifiedEntranceMessage.newBuilder()
                .setHead(BusinessProtocolMessageStandard.Head.newBuilder()
                        .setMsgType(head.getMsgType())
                        .setMsgContentType(head.getMsgContentType())
                        .setFromId(head.getFromId())
                        .setToId(head.getToId())
                        .setTimestamp(head.getTimestamp())
                        .setStatusReport(IMSConfig.STATUS_REPORT_RECEIPT_OFFLINE)
                        .setUniqueIdentify(head.getUniqueIdentify())
                        .setToken(head.getToken())
                        .build())
                .build();
        return BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage.newBuilder().setUnifiedEntranceMessage(msg).build();
    }
}
